package com.taxx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxx.entity.SysMenu;
import com.taxx.mapper.SysMenuMapper;
import com.taxx.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统菜单服务实现类
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private SysMenuMapper menuMapper;

    @Override
    public List<SysMenu> getMenuList() {
        return menuMapper.selectEnabledMenus();
    }

    @Override
    public List<SysMenu> getMenuTree() {
        List<SysMenu> allMenus = menuMapper.selectEnabledMenus();
        return buildMenuTree(allMenus);
    }

    @Override
    public SysMenu getMenuById(Long id) {
        return getById(id);
    }

    @Override
    public boolean createMenu(SysMenu menu) {
        // 检查菜单编码是否已存在
        QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("menu_code", menu.getMenuCode());
        if (count(wrapper) > 0) {
            throw new RuntimeException("菜单编码已存在");
        }

        menu.setStatus(1); // 默认启用
        menu.setVisible(1); // 默认显示
        return save(menu);
    }

    @Override
    public boolean updateMenu(SysMenu menu) {
        // 检查菜单编码是否已被其他菜单使用
        QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("menu_code", menu.getMenuCode())
                .ne("id", menu.getId());
        if (count(wrapper) > 0) {
            throw new RuntimeException("菜单编码已存在");
        }

        return updateById(menu);
    }

    @Override
    public boolean deleteMenu(Long id) {
        // 检查是否有子菜单
        QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        if (count(wrapper) > 0) {
            throw new RuntimeException("请先删除子菜单");
        }

        return removeById(id);
    }

    @Override
    public boolean updateMenuStatus(Long id, Integer status) {
        SysMenu menu = new SysMenu();
        menu.setId(id);
        menu.setStatus(status);
        return updateById(menu);
    }

    @Override
    public List<SysMenu> getMenusByRoleId(Long roleId) {
        return menuMapper.selectMenusByRoleId(roleId);
    }

    @Override
    public List<SysMenu> getMenusByUserId(Long userId) {
        List<SysMenu> menus = menuMapper.selectMenusByUserId(userId);
        return buildMenuTree(menus);
    }
    
    @Override
    public List<SysMenu> getMenusByUsername(String username) {
        List<SysMenu> menus = menuMapper.selectMenusByUsername(username);
        return buildMenuTree(menus);
    }

    /**
     * 构建菜单树
     */
    private List<SysMenu> buildMenuTree(List<SysMenu> menus) {
        if (menus == null || menus.isEmpty()) {
            return new ArrayList<>();
        }

        // 按父级ID分组
        Map<Long, List<SysMenu>> menuMap = menus.stream()
                .collect(Collectors.groupingBy(menu -> 
                    menu.getParentId() == null ? 0L : menu.getParentId()));

        // 递归构建树结构
        return buildMenuTreeRecursive(0L, menuMap);
    }

    /**
     * 递归构建菜单树
     */
    private List<SysMenu> buildMenuTreeRecursive(Long parentId, Map<Long, List<SysMenu>> menuMap) {
        List<SysMenu> children = menuMap.get(parentId);
        if (children == null) {
            return new ArrayList<>();
        }

        for (SysMenu menu : children) {
            List<SysMenu> childMenus = buildMenuTreeRecursive(menu.getId(), menuMap);
            if (!childMenus.isEmpty()) {
                menu.setChildren(childMenus);
            }
        }

        return children;
    }
}
